package com.mofabot.bot

import cn.hutool.core.util.ClassUtil
import cn.hutool.core.util.StrUtil
import com.mofabot.annotation.CallbackPath
import com.mofabot.annotation.Command
import com.mofabot.utils.LogUtil.Companion.log
import com.mofabot.utils.SpringUtils
import java.util.concurrent.ConcurrentHashMap

/**
 * 初始化指令路由信息
 * 1. 扫描com.mofabot.command包下所有的类
 * 2. 扫描类上的@Command注解，将其value作为路由path，将其desc作为路由描述
 * 3. 将路由path和类实例放入路由表中
 * 4. 扫描类中的所有方法，将其@CallbackPath注解的方法名作为路由path，将其方法名和方法实例放入路由表中
 * 5. 将路由表放入Router.ROUTE中
 *
 * @since 2023/09/19.
 * @author ll
 */
object Router {
    //命令路由
    val ROUTE: ConcurrentHashMap<String, ICommandBase> = ConcurrentHashMap()

    fun initRouter() {

        val annotationClass: Class<out Annotation?> = Command::class.java

        val commandClassList = ClassUtil.scanPackageByAnnotation("com.mofabot.command", annotationClass)
        log.info("Command List : $commandClassList")
        commandClassList.forEach { clz ->
            val clzName = StrUtil.lowerFirst(clz.simpleName)
            val cc: ICommandBase = SpringUtils.getBean(clzName)
            clz.getAnnotation(Command::class.java)?.let {
                ROUTE[it.value] = cc
            }
            //处理callback
            clz.declaredMethods
                .filter { it.annotations.any { annotation -> annotation is CallbackPath } }
                .forEach { cc.callBackMethodMap[it.name] = it }
        }
        log.info("Router Init Finished!")
    }

}
